/*
  Controls the linear actuator/drill servo through a full
  plant cycle 
*/
#ifndef DISPENSER_H
#define DISPENSER_H

#include <Arduino.h>
#include <Servo.h>
#include "Config.h"

enum class DispenseState : uint8_t { IDLE, EXTENDING, SETTLING, RETRACTING };

class Dispenser {
public:
  void begin(uint8_t servoPin);
  void update(unsigned long nowMs, bool hopperHasSeedLive);

  bool isBusy() const { return _state != DispenseState::IDLE; }
  void startPlantCycle();

  // Returns true exactly once the loop iteration a cycle finishes and
  // reports whether a seed was actually detected leaving the hopper.
  bool consumeCompletedCycle(bool &seedDetectedOut);

  bool isHopperEmpty() const { return _hopperEmpty; }
  uint32_t sessionSeedCount() const { return _sessionSeedCount; }

  void refillHopper();       
  void resetSessionCount();

private:
  Servo _servo;
  DispenseState _state = DispenseState::IDLE;
  unsigned long _stateStartMs = 0;

  bool _seedDetectedThisCycle = false;
  bool _cycleCompletePending = false;

  uint8_t _emptyStreak = 0;
  bool _hopperEmpty = false;
  uint32_t _sessionSeedCount = 0;
};

#endif 
